const { exec } = require("child_process");
const path = require("path");
const chalk = require("chalk");

// 定义项目路径
const mainPath = __dirname;
const reactPath = path.join(__dirname, "../react-sub");

// 定义应用信息
const apps = [
  {
    name: "主应用",
    path: mainPath,
    port: 5173,
    command: "yarn dev",
  },
  {
    name: "React子应用",
    path: reactPath,
    port: 3001,
    command: "yarn start",
  },
];

// 美化边框
const box = {
  topLeft: "╭",
  topRight: "╮",
  bottomLeft: "╰",
  bottomRight: "╯",
  horizontal: "─",
  vertical: "│",
};

// 创建分隔线
const createLine = (width = 50) => box.horizontal.repeat(width);

// 创建带边框的文本框
const createBox = (text, width = 50) => {
  const padding = Math.max(0, width - text.length - 2);
  const leftPad = Math.floor(padding / 2);
  const rightPad = padding - leftPad;
  return [
    `${box.topLeft}${createLine(width)}${box.topRight}`,
    `${box.vertical}${" ".repeat(leftPad)}${text}${" ".repeat(rightPad)}${
      box.vertical
    }`,
    `${box.bottomLeft}${createLine(width)}${box.bottomRight}`,
  ].join("\n");
};

// 检查是否需要安装依赖
const checkAndInstall = (projectPath) => {
  return new Promise((resolve, reject) => {
    if (!require("fs").existsSync(path.join(projectPath, "node_modules"))) {
      console.log(
        chalk.yellow(`📦 正在安装 ${path.basename(projectPath)} 依赖...`)
      );
      exec("yarn install", { cwd: projectPath }, (error) => {
        if (error) {
          reject(error);
          return;
        }
        resolve();
      });
    } else {
      resolve();
    }
  });
};

// 启动项目
const startProject = (app) => {
  return new Promise((resolve) => {
    console.log(chalk.cyan(`🚀 正在启动 ${app.name}...`));
    const child = exec(app.command, { cwd: app.path });

    let isStarted = false;

    child.stdout.on("data", (data) => {
      if (
        data.includes("App running at:") ||
        data.includes("Local:   http://") ||
        data.includes("localhost:") ||
        data.includes("successfully") ||
        data.includes("ready in")
      ) {
        if (!isStarted) {
          isStarted = true;
          console.log(
            chalk.green(`✨ ${app.name}已启动: http://localhost:${app.port}`)
          );
          resolve();
        }
      } else if (data.includes("ERROR")) {
        console.log(chalk.red(`❌ [${app.name}] ${data}`));
      }
    });

    child.stderr.on("data", (data) => {
      if (data.includes("ERROR")) {
        console.error(chalk.red(`❌ [${app.name}] ${data}`));
      }
    });

    setTimeout(() => {
      if (!isStarted) {
        console.log(chalk.yellow(`⚠️  ${app.name}启动时间较长，但仍在继续...`));
      }
    }, 10000);
  });
};

// 主函数
async function startAll() {
  console.clear();
  console.log(
    "\n" + chalk.blue(createBox(" 🌟 无界微前端启动程序 ", 48)) + "\n"
  );

  try {
    console.log(chalk.blue("📋 [1/2] 检查依赖..."));
    await Promise.all(apps.map((app) => checkAndInstall(app.path)));

    console.log(chalk.blue("\n🚀 [2/2] 启动应用...\n"));
    await Promise.all(apps.map((app) => startProject(app)));

    // 创建应用信息表格
    console.log("\n" + chalk.green(createBox(" ✅ 所有应用启动成功 ", 48)));
    console.log(chalk.white("\n📌 应用访问地址："));
    console.log(chalk.gray(createLine(48)));

    apps.forEach((app) => {
      console.log(
        chalk.cyan(`  ${app.name.padEnd(12)}`) +
          chalk.yellow(`➜  http://localhost:${app.port}`)
      );
    });

    console.log(chalk.gray(createLine(48)));
    console.log(
      chalk.gray("\n💡 提示：主应用已集成所有子应用，访问主应用即可\n")
    );
  } catch (error) {
    console.error(chalk.red("\n❌ 启动失败："), error);
    process.exit(1);
  }
}

startAll();
